<template>
  <!-- 产品管理 -->
  <div class="multicolumn">
  <div class="container">
    <section class="left-container">
      <el-tree
        :data="data"
        :props="defaultProps"
        :expand-on-click-node="false"
        node-key="id"
        class="tree-wrapper"
        :default-expanded-keys="idArr"
        @node-click="getList2($event,page,2,orderBy.name, orderBy.method)"
      >
        <span class="custom-tree-node show-hide" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span style="visibility:hidden;">
            <el-button style="margin-left:10px" type="text" size="mini" @click="addNode(node, data)" v-if="hasPermission('product:category:add')"
            >新增</el-button
            >
            <el-button type="text" size="mini" v-if="node.level!==1" @click="editNode(node, data)">修改</el-button>
            <el-button type="text" size="mini" v-if="node.level!==1" @click="delNode( data)">删除</el-button>
          </span>
        </span>
      </el-tree>
    </section>

    <section class="right-container">

      <div>
        <el-button
          type="primary"
          size="small"
          @click="add"
        ><span>新增</span></el-button
        >
        <section class="right-but" style="display:flex">
            <el-button style="cursor:pointer;" type="text"
                       @click="exportExcel(page, 1,productCategoryId, orderBy.name, orderBy.method)">
                <img src="~@/assets/img/export.png" alt="">
            </el-button>
          <el-button type="text" style="margin-right:-13px"  @click="getList(page, 2,productCategoryId,orderBy.name,orderBy.method,queryForm.name,queryForm.checkedState)">
            <img style="width:44px;height:36px;" src="~@/assets/img/shuaxin.png" >
          </el-button>
          <PopoverBut :checkedProps="checkedProps"  :options="options" @getCheckeds="handlerCloumn"></PopoverBut>

        </section>
      </div>

      <el-table
        size="mini"
        v-loading="loading"
        :data="tableData"
        style="width: 100%; margin-top: 10px"
        border
        :header-cell-style="{
          'background-color': '#eeeeee !important',
        }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="index" label="序号" width="70">
          <template slot-scope="scope">
            <span>{{
                (page.pageNo - 1) * page.pageSize + scope.$index + 1
              }}</span>
          </template>

        </el-table-column>
        <el-table-column prop="productCategoryName" label="目录" min-width="120"> </el-table-column>
        <el-table-column prop="name" label="原料名称" min-width="120"> </el-table-column>
        <span v-for="(item,index) in checkedProps" :key="index">
          <el-table-column prop="createBy.loginName"  min-width="110" :label="item" v-if="item ==='创建人'">
              <template slot-scope="scope">
                  <span v-if="scope.row.createBy">{{scope.row.createBy.loginName | noValue}}</span>
              </template>
          </el-table-column>
        <el-table-column prop="createDate" :label="item"  min-width="200" v-if="item === '创建时间'">
            <template slot-scope="scope">
                {{scope.row.createDate | noValue}}
            </template>
        </el-table-column>
          <el-table-column prop="updateBy.loginName"  min-width="120" :label="item" v-if="item ==='上次操作人'">
              <template slot-scope="scope">
                  {{scope.row.updateBy.loginName | noValue}}
              </template>
          </el-table-column>
        <el-table-column prop="updateDate" :label="item" min-width="200" v-if="item === '上次操作时间'">
            <template slot-scope="scope">
                {{scope.row.updateDate | noValue}}
            </template>
        </el-table-column>
        </span>
        <el-table-column prop="state" label="状态" sortable="custom" min-width="110px">
          <template slot-scope="scope">
            <section class="activate-state" v-if="scope.row.state===1">
              <i></i>
               {{$dictUtils.getDictLabel("state", scope.row.state, "")}}
            </section>
            <section class="inactive-state" v-else>
              <i></i>
              {{$dictUtils.getDictLabel("state", scope.row.state, "")}}
            </section>
          </template>
        </el-table-column>

        <el-table-column prop="address" label="操作" width="176">
          <template slot-scope="scope">
            <template v-for="item in $dictUtils.getDictList('state')">
              <!--<el-link type="primary" v-if="item.value !=='-1'&& item.value!==(scope.row.state+'')" :underline="false" @click="editState(item.value,scope.row)"  :disabled="(scope.row.state===-1&& item.value==='0')||item.value==scope.row.state"
              >{{item.label}}
              </el-link>-->
              <span v-if="scope.row.state === -1 || scope.row.state === 0" class="operation">
                <el-link type="primary"  v-if="item.value ==='1'"
                         :underline="false" @click="editState(item.value,scope.row)">{{item.label}}
              </el-link>
              </span>
              <span v-if="scope.row.state === 1"  class="operation">
                <el-link type="primary"  v-if="item.value ==='0'"
                         :underline="false" @click="editState(item.value,scope.row)">{{item.label}}
              </el-link>
              </span>
            </template>
            <el-link type="primary" :underline="false" @click="edit(scope.row)"
            >修改</el-link
            >
            <el-link
              type="primary"
              :underline="false"
              @click="isCheck(scope.row)"
            >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="page.pageSize"
        :current-page="page.pageNo"
        layout="total,sizes,prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
      <EditForm
        ref="EditForm"
        @refreshDataList="getList(page, 2,productCategoryId, orderBy.name, orderBy.method)"
      ></EditForm>
      <TreeForm ref="treeForm" @refreshDataList="getTreeData(0,1)"></TreeForm>
    </section>
  </div>
  </div>
</template>
<script>
  // import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  // import { getList, delCrm, editState } from '@/api/market/crm.js'
  // import { getList, delCrm, editState } from '@/api/market/crm.js'
  import { getTreeData,getCategory, getList, editState, delProduct, delTreeData, getById, isCheck} from '@/api/market/product.js'
  import EditForm from './editForm'
  import TreeForm from './treeForm'
  import PopoverBut from '@/components/button/popoverBut'
  const options1 = []
  const cityOptions = ['上海', '北京']
  export default {
    components: {
      EditForm,
      PopoverBut,
      TreeForm
    },

    data () {
      return {
        categoryData: {},
        idArr: [],
        value: null,
        // define options
        options2: [ {
          id: 'a',
          label: 'a',
          s: 's',
          children: [ {
            id: 'aa',
            label: 'aa',
            s: 's'
          }, {
            id: 'ab',
            label: 'ab',
            s: 's'
          } ]
        } ],
        dialogVisible: false,
        query: '',
        productList: [],
        inputForm: {
          parentId: 0
        },
        data: [],
        defaultProps: {
          // 修改el-tree默认data数组参数
          label: 'name',
          id: 'id',
          parentId: 'parentId',
          children: 'children'
        },
        checkedProps: options1,
        ShowCloum: { createDate: '' },
        options: [
          { label: '创建人', key: 'createBy.loginName' },
          { label: '创建时间', key: 'createDate' },
          { label: '上次操作人', key: 'updateBy.loginName' },
          { label: '上次操作时间', key: 'updateDate' }
        ],
        tableData: [],
        orderBy: {
          name: 'update_date',
          method: 'desc'
        },
        loading: false,
        page: {
          pageSize: 10,
          pageNo: 1,
          total: 0
        },
        props: 1,
        queryForm: {
          checkedCities: 0
        },
        checkedCities: [],
        productCategoryId: '',
        cities: cityOptions
      }
    },
    methods: {
      // 校验：产品是否被业务使用
      isCheck (row) {
        isCheck({
          id: row.id
        }).then((res) => {
          if (JSON.stringify(res.data.result)!=="[]") {
            this.$notify.error({
              title: '错误',
              message: '该原料已使用，不支持删除！'
            })
          } else {
            this.del(row.id)
          }
        });

      },
      getOption (e, s) {
        console.log(e)
        console.log(s)
      },
      getTreeData2 () {
        getTreeData().then(res => {
          if (res.data.code === '200') {
            this.productList = res.data.result
          }
          console.log(this.productList)
        })
      },
      // 获取产品目录
      getTreeData (id, types) {
        getTreeData({ types: types
        }).then((res) => {
          if (res.data.code === '200') {
            this.data = res.data.result
            this.data.forEach(m => {
              this.idArr.push(m.id)
            })
          }
        })
      },
      getList2 ($event, params, types, orderName, orderByAORC, queryNames, queryState) {
        console.log($event)
        console.log(types)
        this.productCategoryId = $event.id
        params.pageNo = 1
        this.categoryData = $event
        this.loading = true
        getList({
          pageSize: params.pageSize,
          pageNo: params.pageNo,
          productCategoryId: $event.id,
          types: types,
          orderBy: orderName,
          orderByAORC: orderByAORC,
          names: queryNames,
          state: queryState
        }).then((res) => {
          if (res.data.code === '200') {
            this.tableData = res.data.result.list

            this.page.total = res.data.result.count
          }
          this.loading = false
        })
      },
      // 获取列表带分页
      getList (params, types, productCategoryId, orderName, orderByAORC, queryNames, queryState) {
        this.loading = true
        getList({
          pageSize: params.pageSize,
          pageNo: params.pageNo,
          productCategoryId: productCategoryId,
          types: types,
          orderBy: orderName,
          orderByAORC: orderByAORC,
          names: queryNames,
          state: queryState
        }).then((res) => {
          if (res.data.code === '200') {
            this.tableData = res.data.result.list
            console.log(this.tableData)
            this.page.total = res.data.result.count
          }
          this.loading = false
        })
      },
      // 删除产品
      del (ids) {
        this.$confirm('此操作将永久删除该原料数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((res) => {
          delProduct({
            ids: ids
          }).then((res) => {
            if (res.data.code === '200') {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList(this.page, 2, this.productCategoryId, this.orderBy.name, this.orderBy.method);
            }
          })
        })
      },
      // 添加
      add () {
        this.$refs.EditForm.init('add', this.categoryData)
      },
      // 编辑
      edit (row) {
        getById({id: row.id}).then((res) => {
          if (res.data.code === '200') {
            let editForm = {}
            editForm.types = res.data.result.types
            editForm.id = res.data.result.id
            editForm.name = res.data.result.name
            editForm.productCategoryName = res.data.result.productCategoryName
            editForm.productCategoryId = res.data.result.productCategoryId
            this.$refs.EditForm.init('edit', editForm)
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            })
          }
        })
      },
      // 改变产品状态
      editState (event, row) {
        this.$confirm(event === '0' ? '停用后，该原料都会将不可用，确认停用吗？' : '您是否要' + this.$dictUtils.getDictLabel("state", event, "") + '?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((res) => {
          editState({id: row.id, state: event}).then((res) => {
            if (res.data.code === '200') {
              this.getList(this.page, 2, this.productCategoryId, this.orderBy.name, this.orderBy.method)
              if (row.state === '1') {
                this.$message({
                  type: 'success',
                  message: '已启用'
                });
              } else if (row.state === '0') {
                this.$message({
                  type: 'success',
                  message: '已停用'
                });
              }
            }
          })
        });
      },
      loadNode (node, resolve) {
        // if (node.level === 0) {
        //   this.getTreeData(0, resolve)

        // }else{
        //    console.log(node.data)
        //   this.getTreeData(node.data.id,resolve)

        // }
        // console.log(node)
        setTimeout(() => {
          let treeNodeBuffer = [
            {
              id: Math.random() * 20, // 动态id  element官网例子没问题
              name: '王小虎王小虎王小虎王小虎',
              parentId: Math.random() * 20,
              ss: Math.random() * 20,
              isLeaf: true
            },
            {
              id: Math.random() * 20, // 动态id  element官网例子没问题
              name: '王小虎',
              parentId: Math.random() * 20,
              isLeaf: false
            }
          ]
          resolve(treeNodeBuffer)
        }, 1000)
      },
      addNode (node, data) {
        this.$refs.treeForm.init('add', node, data)

        console.log(node)
        console.log(data)
      },
      editNode (node, data) {
        this.$refs.treeForm.init('edit', node, data)
        console.log(node)
        console.log(data)
      },
      // 删除树形目录
      delNode (data) {
        this.$confirm('确认删除该目录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((res) => {
          delTreeData({id: data.id, delFlags: 0}).then(res => {
            this.getTreeData(0, 1);
            if (res.data.code === 'A120501') {
              this.$confirm(res.data.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then((res) => {
                delTreeData({id: data.id, delFlags: 1}).then(res => {
                  if (res.data.code === '200') {
                    this.$message({
                      type: 'success',
                      message: '已删除!'
                    })
                    this.getTreeData(0, 1);
                  }
                })
              });
            }
          })
        });

      },
      // 是否显示某列数据
      handlerCloumn (e) {
        this.checkedProps = e
        // console.log(e)
      },
      // 重置查询条件
      reset () {
        this.queryForm = {}
          this.getList(this.page, 2, this.productCategoryId, this.orderBy.name, this.orderBy.method)
      },
        exportExcel (params, types, productCategoryId, orderName, orderByAORC, queryNames, queryState) {
            this.$http({
                method: 'get',
                url: '/basis/product/product/export',
                params: {
                    pageSize: params.pageSize,
                    pageNo: params.pageNo,
                    productCategoryId: productCategoryId,
                    types: 2,
                    orderBy: orderName,
                    orderByAORC: orderByAORC,
                    names: queryNames,
                    state: queryState
                },
                responseType: 'blob'
            }).then(response => {
                if (!response) {
                    return
                }
                let link = document.createElement('a')
                link.href = window.URL.createObjectURL(new Blob([response.data]))
                link.target = '_blank'
                let filename = response.headers['content-disposition']
                link.download = decodeURI(filename)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
                // eslint-disable-next-line handle-callback-err
            }).catch((error) => {

            })
        },
      // 排序
      sortthiscolumn (a) {
        this.orderBy.name = a.prop
        this.page.pageNo = 1
        if (a.order === 'ascending') {
          this.orderBy.method = 'asc'
        } else {
          this.orderBy.method = 'desc'
        }
        this.getList(this.page, 2, this.productCategoryId, this.orderBy.name, this.orderBy.method)
      },
      handleSizeChange (e) {
        this.page.pageSize = e
        this.getList(this.page, 2,this.productCategoryId, this.orderBy.name, this.orderBy.method)
      },
      handleCurrentChange (e) {
        this.page.pageNo = e
        this.getList(this.page, 2,this.productCategoryId, this.orderBy.name, this.orderBy.method)
        console.log(e)
      },
      tableRowClassName ({ row, rowIndex }) {
        if (rowIndex % 2 === 1) {
          return 'warning-row'
        } else {
          return 'success-row'
        }
      }
    },
    mounted () {
      this.tableData = [{ names: '1' }]
      this.getList(this.page, 2,this.productCategoryId, this.orderBy.name, this.orderBy.method)
      this.getTreeData(0, 1)
    }
  }
</script>
<style lang="scss" scoped>
  @import "@/assets/scss/public.scss";
  ::v-deep .el-tree {
    display: inline-block;
    /*min-width: 120%;*/
  }
  .show-hide {
    width: 100%;
  }
  .show-hide:hover :nth-child(2) {
    visibility:visible !important;
  }
  ::v-deep .el-input--small .el-input__inner {
    height: 36px;
    line-height: 32px;
    width: 230px;
  }
  ::v-deep .el-tabs__content {
    padding: 20px !important;
  }
  .multicolumn{
      margin: -20px;
  }
  .container {
    margin: 0;
  }
  .left-container {
    overflow: auto; /*可滑动*/
    ::v-deep.el-tree{
      .custom-tree-node{
        font-size: 16px;
      }
    }
  }
  .right-container {
    padding: 20px;
  }
  .queryForm {
    position: relative;
    .but-container {
      top: 10px;
      margin-left: 20px;
    }
  }
  .right-but {
    float: right;
  }
  .el-table .success-row {
    background: #f0f9eb;
  }
  ::v-deep .el-table .warning-row {
    background: #f7f7f7;
  }
</style>
